// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

// cc.macro.CLEANUP_IMAGE_CACHE = false;
// cc.dynamicAtlasManager.enabled = false;
// cc.    cc.macro.CLEANUP_IMAGE_CACHE = false;

cc.macro.CLEANUP_IMAGE_CACHE = false;
cc.dynamicAtlasManager.enabled = true;
cc.dynamicAtlasManager.maxFrameSize = 2048

console.log('我的==', cc.dynamicAtlasManager.enabled);
const { ccclass, property } = cc._decorator;

@ccclass
export default class YFDrawCallView extends cc.Component {

    @property({ tooltip: "itemCell，高亮状态,节点名称" })//会多一层线性合批，如果列表没有选中效果就不选
    itemChoseRootName: string = '';
    @property(cc.ScrollView)
    scrollView: cc.ScrollView = null
    onLoad() {
        // cc.macro.CLEANUP_IMAGE_CACHE = false;
        // cc.dynamicAtlasManager.enabled = false;
        // cc.dynamicAtlasManager.maxFrameSize = 2048
        this.InitView()

        this.node.on(cc.Node.EventType.CHILD_ADDED, (child) => {
            console.log("Child added to layout:", child.name, this.node.childrenCount);
            //  this.ReloadAll();
        });

        this.node.on(cc.Node.EventType.CHILD_REMOVED, (child) => {
            console.log("Child removed from layout:", child.name);
            // 在这里执行你的逻辑，处理子节点移除后的操作
            // this.ReloadAll();
        });
    }

    protected start(): void {
        // 注册 Layout 组件的布局子节点回调


        console.log("容器布局变了=", this.node.getContentSize());

        // this.node.on(cc.Node.EventType.CHILD_ADDED, (child) => {
        //     console.log("Child added to layout:", child.name, this.node.childrenCount);
        //     //  this.ReloadAll();

        // });

        // this.node.on(cc.Node.EventType.CHILD_REMOVED, (child) => {
        //     console.log("Child removed from layout:", child.name);
        //     // 在这里执行你的逻辑，处理子节点移除后的操作
        //     // this.ReloadAll();
        // });

        if (this.scrollView) {
            this.scrollView.node.on('scrolling', this.updateItem, this);
        }


    }



    public FindNode(superNodeName: string, tartgetName: string): cc.Node {
        return this.itemRootNode.get(superNodeName)
    }

    public opacity(superNodeName: string, opacity: number) {
        this.Hide(superNodeName, false, opacity)
    }

    public active(superNodeName: string, active: boolean) {
        this.Hide(superNodeName , true, active)
    }

    //删除item元素
    public RemoveItemNode(name: string) {
        let resultKeyList = this.FindNodeKey(name)
        //console.log('kkkk=',resultKeyList);
        for (let index = 0; index < resultKeyList.length; index++) {
            const key: string = resultKeyList[index];
            let node: cc.Node = this.itemRootNode.get(key)
            //  console.log(key, node)
            node.destroy()

            this.itemRootNode.delete(key)
            this.itemRootNodePos.delete(key)

        }

        // console.log('---', this.itemRootNode);
        this.ReloadAll()
    }

    updateItem() {
        this.ReloadAllPos()
    }



    content: cc.Node;
    private labelRoot: cc.Node;
    private imageRoot: cc.Node;

    private labelRootChose: cc.Node;
    private imageRootChose: cc.Node;

    public itemRootNode: Map<string, cc.Node> = new Map()//每个item根节点
    public itemRootNodePos: Map<string, cc.Vec3> = new Map()//每个item根节点
    public componentAll: Map<string, cc.Node> = new Map()//每个item根节点


    private itemChoseRootNameNode: any = {}//每个item的选中节点

    private InitView() {
        let siblingIndex = this.node.getSiblingIndex();

        this.content = new cc.Node('lineView');
        this.node.parent.addChild(this.content);
        this.content.setSiblingIndex(siblingIndex + 1)
        this.content.anchorX = this.node.anchorX
        this.content.anchorY = this.node.anchorY
        this.content.setContentSize(this.node.getContentSize())
        this.content.position = this.node.position


        this.node.on(cc.Node.EventType.POSITION_CHANGED, this.onPositionChanged, this);
        this.node.on(cc.Node.EventType.SIZE_CHANGED, this.onSizeChanged, this);

        this.labelRoot = new cc.Node('label_root');
        this.imageRoot = new cc.Node('image_root');
        this.content.addChild(this.imageRoot)
        this.content.addChild(this.labelRoot)
        this.labelRoot.position = cc.v3(10, 0, 0)
        this.imageRoot.position = cc.v3(10, 0, 0)

        if (this.itemChoseRootName != '') {
            //选中效果
            this.labelRootChose = new cc.Node('label_root_chose');
            this.imageRootChose = new cc.Node('image_root_chose');
            this.content.addChild(this.imageRootChose)
            this.content.addChild(this.labelRootChose)
            this.labelRootChose.position = cc.v3(0)
            this.imageRootChose.position = cc.v3(0)
        }

        // this.ReloadAll()
    }

    onPositionChanged() {
        this.content.position = this.node.position
        //console.log("2容器布局变了");
    }

    onSizeChanged() {
        console.log("容器布局变了", this.node.getContentSize());


        this.content.setContentSize(this.node.getContentSize())
    }

    public ReloadAll() {

        //   let time1 = Date.now()
        let layout = this.node.getComponent(cc.Layout)
        if (layout) {
            layout.updateLayout()
        }
        let content = this.node;
        let count = content.childrenCount
        //  console.log(content.children)
        for (let index = 0; index < count; index++) {
            let subObj = content.children[index]
            if (subObj.name === '') {
                console.log('销毁')
                continue;
            }
            if (subObj.name === this.labelRoot.name || subObj.name === this.imageRoot.name

            ) {
                continue
            }

            if (this.itemChoseRootName.length > 0) {
                if (subObj.name === this.labelRootChose.name || subObj.name === this.imageRootChose.name) {
                    continue
                }
                if (subObj.name === this.labelRootChose.name || subObj.name === this.imageRootChose.name) {
                    continue
                }
            }
            this.itemRootNode.set(subObj.name, subObj)
            this.itemRootNodePos.set(subObj.name, subObj.position.clone())

            let list = [...subObj.children];
            for (let i = 0; i < list.length; i++) {
                let obj = list[i];
                let active = obj.parent.active ? obj.active : false;
                let opacity = obj.parent.opacity === 255 ? obj.opacity : 0;

                if (this.itemChoseRootName === obj.name) {
                    this.SetSubObj(obj, this.labelRootChose, this.imageRootChose, active, opacity, subObj.name, subObj.name)
                } else {
                    this.SetSubObj(obj, this.labelRoot, this.imageRoot, active, opacity, subObj.name, subObj.name)
                }
            }
        }

        console.log("1输出", this.itemRootNode);
        //  this.itemChoseRootNameNode = this.FindSelectNode(this.itemRootNode, this.itemChoseRootName)
        console.log("2位置输出", this.itemRootNodePos);
        this.ReloadAllPos()
        //   let time2 = Date.now()

        //   console.log('耗时',time2-time1);
    }

    //刷新位置
    private ReloadAllPos() {
        let keys = Array.from(this.componentAll.keys())
        for (let index = 0; index < keys.length; index++) {
            const key = keys[index];
            let sub: cc.Node = this.componentAll.get(key);
            let superNode:cc.Node = this.itemRootNode.get((key.split('/'))[0])
            if (sub.name === '' || superNode.name === '') {
                continue;
            }
            let pos: cc.Vec3 = this.itemRootNodePos.get(key)
            let wp = superNode.convertToWorldSpaceAR(pos);
            let localPosition2 = this.ToLocalPosition(sub.parent, wp)
            sub.position = localPosition2;
            //解决tableview 重用 不显示的问题
            let temp_key = key.split('/')
            let temp_key_target = [superNode.name, this.itemChoseRootName]
            if (!this.arraysAreEqual(temp_key_target, temp_key)) {
                sub.active = superNode.active;
                sub.opacity = superNode.opacity;
            }

    
        }
    }

    public ReloadAllPosCeShi(op) {
        let keys = Array.from(this.itemRootNode.keys())
        for (let index = 0; index < keys.length; index++) {
            const key = keys[index];
            let sub: cc.Node = this.itemRootNode.get(key);

            if (sub.name === '') {
                // console.log('销毁')
                continue;
            }
            // console.log(sub)
            if (sub.getComponent(cc.Label) || sub.getComponent(cc.Sprite)) {
                let superNode = this.itemRootNode.get((key.split('/'))[0])
                //  console.log('父',superNode.name);
                let pos: cc.Vec3 = this.itemRootNodePos.get(key)
                let wp = superNode.convertToWorldSpaceAR(pos);
                let localPosition2 = this.ToLocalPosition(sub.parent, wp)

                sub.active = op
                sub.position = localPosition2;
            }
        }
    }


    Hide(name: string, isActiveOrOpacity: boolean, value: any) {
        let resultKeyList = this.FindNodeKey(name)
      //  console.log('----', resultKeyList,name)
        for (let index = 0; index < resultKeyList.length; index++) {
            const element = resultKeyList[index];
            if (isActiveOrOpacity) {
                (<cc.Node>this.itemRootNode.get(element)).active = value;
            } else {
                (<cc.Node>this.itemRootNode.get(element)).opacity = value;
            }
        }
    }



    private FindNodeKey(name: string) {
        if (!name || name.length <= 0) {
            return []
        }
        let resultKeyList = []

        let keys = Array.from(this.itemRootNode.keys())
        // console.log('keys=',keys);
        for (let index = 0; index < keys.length; index++) {
            const key = keys[index];
            let temp_key = key.split('/')
            let temp_key_target = name.split('/')

            if (this.arraysAreEqual(temp_key_target, temp_key)) {
                resultKeyList.push(key)
            }
        }

        return resultKeyList
    }

    private SetSubObj(subObj: cc.Node, labelRoot, imageRoot, active: boolean, opacity: number, superName: string, rootName: string) {
        if (!subObj) {
            return
        }

        if (subObj.childrenCount > 0) {
            let superKey = superName + "/" + subObj.name
            this.itemRootNode.set(superKey, subObj)
            let superNode: cc.Node = this.itemRootNode.get(rootName);
            let localPosition1 = this.ToLocalPosition(superNode, this.ToWorldPosition(superNode, subObj))
            this.itemRootNodePos.set(superKey, localPosition1.clone())

            let isLabel = subObj.getComponent(cc.Label)
            let isImage = subObj.getComponent(cc.Sprite)
            if (isLabel || isImage) {
                console.log('---',rootName)
                this.SetSub(subObj, labelRoot, imageRoot, active, opacity, superName)
            }

            let list = [...subObj.children];

            // subObj.active = active
            // subObj.opacity = opacity

            for (let index = 0; index < list.length; index++) {
                const element = list[index];
                if (element.name === '') {
                    console.log('销毁')
                    continue;
                }
                // element.active = active
                // element.opacity = opacity

               let  key_2 = superKey + "/" + element.name;
                this.itemRootNode.set(key_2, element);

                let localPosition1 = this.ToLocalPosition(superNode, this.ToWorldPosition(superNode, element))
                this.itemRootNodePos.set(key_2, localPosition1.clone())
              //  console.log('销毁--', key_2)

                this.SetSubObj(element, labelRoot, imageRoot, active, opacity, superKey, superName)
            }
        } else {
            this.SetSub(subObj, labelRoot, imageRoot, active, opacity, superName)
        }

    }
    SetSub(subObj: cc.Node, labelRoot, imageRoot, active: boolean, opacity: number, superName: string) {


        let isLabel = subObj.getComponent(cc.Label)
        let isImage = subObj.getComponent(cc.Sprite)


        if (isLabel || isImage) {
            let superKey = superName + "/" + subObj.name
            this.itemRootNode.set(superKey, subObj)
            let superNode: cc.Node = this.itemRootNode.get(superName);
            let localPosition1 = this.ToLocalPosition(superNode, this.ToWorldPosition(superNode, subObj))
            this.itemRootNodePos.set(superKey, localPosition1.clone())
            this.componentAll.set(superKey, subObj)
        }
        if (isLabel) {
            let superNode: cc.Node = this.itemRootNode.get(superName);

            let localPosition1 = this.ToLocalPosition(labelRoot, this.ToWorldPosition(superNode, subObj))
            subObj.parent = labelRoot
            subObj.position = cc.v3(localPosition1)
            subObj.active = active
            subObj.opacity = opacity

        }

        if (isImage) {
            let superNode: cc.Node = this.itemRootNode.get(superName);

            let localPosition1 = this.ToLocalPosition(imageRoot, this.ToWorldPosition(superNode, subObj))

            subObj.parent = imageRoot
            subObj.position = cc.v3(localPosition1)
            subObj.active = active
            subObj.opacity = opacity
        }
    }


    //获取世界坐标
    ToWorldPosition(superNode, node: any) {
        // return (<cc.Node>node).convertToWorldSpaceAR(cc.Vec3.ZERO);

        //  console.log('---', node.parent.name);
        return node.parent.convertToWorldSpaceAR(node.position);

    }

    //获取本地坐标
    ToLocalPosition(node: any, worldPosition: any) {
        return (<cc.Node>node).convertToNodeSpaceAR(worldPosition);
    }


    arraysAreEqual(arr1: any[], arr2: any[]): boolean {
        // 首先检查数组的长度
        // if (arr1.length !== arr2.length) {
        //     return false;
        // }

        // 逐一比较数组的每个元素
        for (let i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) {
                // 如果发现有不相等的元素，返回 false
                return false;
            }
        }
        // 如果所有元素都相等，则返回 true
        return true;
    }
    // update (dt) {}
}
